//
//  YWNewWorkNoticeTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/5.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWNewWorkNoticeTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "MBProgressHUD.h"
#import "NSDate+Additions.h"

#import "YWPatrolPicture.h"
//#import "YWImageView.h"
#import "YWPhotoView.h"
#import "YWTextFieldCell.h"
#import "YWWriteNoteCell.h"
#import "YWTakePhotoCell.h"

#import "YWContactManager.h"
#import "YWHandler.h"
#import "YWTempMissionManager.h"
#import "YWSelectContactTableViewController.h"

static CGFloat const kDatePickerViewH = 216;

@interface YWNewWorkNoticeTableViewController ()<YWWriteNoteCellDelegate,YWTakePhotoCellDelegate,YWTextFieldCellDelegate,YWContactVCSelectContactDelegate>{
    NSString *tempMissionTitle;
    NSString *tempMissionContent;
    NSString *cutOffTimeString;
    BOOL isShowDatePicker;
}
@property (nonatomic, strong) NSMutableArray *selectedHandlerArray;
@property (nonatomic, strong) NSArray *totalImageNameArray;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, weak) MBProgressHUD* HUD;
@end

@implementation YWNewWorkNoticeTableViewController
- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"newTempMission", nil);//@"新建临时任务";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", nil) style:UIBarButtonItemStylePlain target:self action:@selector(clickCancelBarButtonEvent:)];
    
    [self initTableView];
    
    //键盘弹起的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

- (NSMutableArray *)selectedHandlerArray{
    if (!_selectedHandlerArray) {
        _selectedHandlerArray = [NSMutableArray array];
    }
    return _selectedHandlerArray;
}

- (void)initTableView{
    [self.tableView registerClass:[YWTextFieldCell class] forCellReuseIdentifier:YWTextFieldCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWTakePhotoCell class] forCellReuseIdentifier:YWTakePhotoCellIdentifier];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
    NSDate *date = [NSDate dateTomorrow];
    NSDateFormatter *formatter = [self dateFormatter];
    NSString *string = [formatter stringFromDate:date];
    cutOffTimeString = string;
    [self.datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, kDatePickerViewH)];
}

- (NSDateFormatter*)dateFormatter
{
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    }
    return _dateFormatter;
}
#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0) {
        return 44;
    }else if (indexPath.section == 1){
        return 44;
    }else if (indexPath.section == 2){
        return 90;
    }else if (indexPath.section == 3){
        return 44;
    }else if (indexPath.section == 4){
        CGFloat imageH = YWPhotoSize*(self.totalImageNameArray.count/4+1) + YWPhotoGap*(self.totalImageNameArray.count/4);
        return 10*2 + imageH;
    }else{
        return 0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section==1? (self.selectedHandlerArray.count>0?self.selectedHandlerArray.count:1) : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YWTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTextFieldCellIdentifier];
        cell.delegate = self;
        cell.textFieldPlaceholder = NSLocalizedString(@"pleaseEnterTheTitle", nil);
        return cell;
    }else if (indexPath.section == 1 || indexPath.section == 3){
        static NSString *cellIdentifier = @"YWNewWorkNoticeTableVCReuseCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.font = kContentFont;
        }
        if (indexPath.section == 1) {
            if (self.selectedHandlerArray.count>0) {
                YWHandler *handler = self.selectedHandlerArray[indexPath.row];
                cell.textLabel.text = handler.userName?:@"";
            }else{
                cell.textLabel.text = NSLocalizedString(@"pleaseSelectExecutor", nil);//@"请选择执行人";
            }
            return cell;
        }else{
            NSString *time = cutOffTimeString ? cutOffTimeString : NSLocalizedString(@"pleaseSelectDeadline", nil);
            cell.textLabel.text = time;
            return cell;
        }
        
    }else if (indexPath.section == 2){
        YWWriteNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.delegate = self;
        cell.textViewPlaceHolder = NSLocalizedString(@"pleaseWriteTheContentOfMission", nil);//@"填写任务内容";
        return cell;
    }else{
        YWTakePhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTakePhotoCellIdentifier];
        cell.delegate = self;
        cell.pickFromPhotoLibrary = YES;
        cell.totalImageNameArray = self.totalImageNameArray;
        return cell;
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (indexPath.section == 1 && [self.selectedHandlerArray count]>0) ? UITableViewCellEditingStyleDelete : UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1 && [self.selectedHandlerArray count]>0) {
        [self.selectedHandlerArray removeObjectAtIndex:indexPath.row];
        if (self.selectedHandlerArray.count==0) {
            [tableView reloadData];
        }else{
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWNewNoticeTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return NSLocalizedString(@"titleOfMission", nil);//@"任务标题";
    }else if (section==1){
        return NSLocalizedString(@"executor", nil);//@"执行人";
    }else if (section==2){
        return NSLocalizedString(@"contentOfMission", nil);//@"任务内容";
    }else if (section==3){
        return NSLocalizedString(@"deadline", nil);//@"截止时间";
    }else if (section==4){
        return NSLocalizedString(@"addPhotos", nil);//@"添加图片";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        YWSelectContactTableViewController *selectContactVC = [[YWSelectContactTableViewController alloc] init];
        selectContactVC.delegate = self;
        selectContactVC.isMultiSelect = YES;
        selectContactVC.ownContacts = self.selectedHandlerArray;
        selectContactVC.titleName = NSLocalizedString(@"selectExecutor", nil);//@"选择执行人";
        [self.navigationController pushViewController:selectContactVC animated:YES];
    }else if (indexPath.section ==3){
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height -self.tableView.bounds.size.height) animated:YES];
        isShowDatePicker = YES;
        [UIView animateWithDuration:0.25 animations:^{
            self.datePicker.frame=CGRectMake(0, SCREEN_HEIGHT-216, SCREEN_WIDTH, 216);
        }];
    }
}

#pragma mark - YWContactVCSelectContactDelegate{
- (void)selectMultipleContact:(NSArray *)contactArray{
//    NSArray* array = [[NSArray alloc] initWithArray:contactArray];
//    self.selectedHandlerArray = array;
    [self.selectedHandlerArray removeAllObjects];
    [self.selectedHandlerArray addObjectsFromArray:contactArray];
    [self.tableView reloadData];
}

#pragma mark - YWTakePhotoCellDelegate
- (void)resetCellFrameWithImages:(NSArray *)images cell:(UITableViewCell *)cell{
    NSArray* array = [[NSArray alloc] initWithArray:images copyItems:YES];
    self.totalImageNameArray = array;
    
    [self.tableView reloadData];
}

#pragma mark - YWTextFieldCellDelegate
- (void)passTextFieldContent:(NSString *)content cell:(UITableViewCell *)cell{
    //标题
    tempMissionTitle = content;
}

#pragma mark - YWWriteNoteCellDelegate
- (void)passNote:(NSString *)note{
    tempMissionContent = note;
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+30*2);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH-20*2;
        
        UIButton *button = [[UIButton alloc] init];
        button.clipsToBounds = YES;
        button.layer.cornerRadius = 4.0;
        button.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        [button setTitle:NSLocalizedString(@"send", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickSenderButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:button];
    }
    return _footView;
}
-(UIDatePicker *)datePicker{
    if (!_datePicker) {
        _datePicker=[[UIDatePicker alloc]init];
        [_datePicker setBackgroundColor:[UIColor whiteColor]];
        _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        _datePicker.locale =[NSLocale localeWithLocaleIdentifier:@"zh"];
        [_datePicker setMinimumDate:[NSDate date]];
        [_datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
        [self.navigationController.view addSubview:_datePicker];
    }
    return _datePicker;
}
-(void)dateChanged:(id)sender{
    UIDatePicker *picker = (UIDatePicker*)sender;
    NSDate *date = picker.date;
    NSDateFormatter *formatter = [self dateFormatter];
    NSString *string = [formatter stringFromDate:date];
    cutOffTimeString = string;
    [self.tableView reloadData];
}
-(void)resetDatePicker{
    isShowDatePicker = NO;
    [UIView animateWithDuration:0.25 animations:^{
        [_datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, kDatePickerViewH)];
    }];
}

- (void)clickSenderButtonEvent:(id)sender{
    [self resetDatePicker];
    if (tempMissionTitle.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseEnterTheTitle", nil)];
        return;
    }
    if (tempMissionTitle.length>50) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"theLengthOfTitleMustBeLessThan50", nil)];
        return;
    }
    if ([YWCommonTool isContainsEmoji:tempMissionTitle]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (tempMissionContent.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseEnterTheContent", nil)];
        return;
    }
    if (tempMissionContent.length>500) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"theLengthOfContentMustBeLessThan500", nil)];
        return;
    }
    if ([YWCommonTool isContainsEmoji:tempMissionContent]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (self.selectedHandlerArray.count == 0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseSelectExecutor", nil)];
        return;
    }
    if (cutOffTimeString.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseSelectDeadline", nil)];
        return;
    }
    //点击发送
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"makeSureToSendTempMission", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        [self postTempMission];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)postTempMission{
    NSArray *pictures = [self createPictures];
    [[YWTempMissionManager shareManager] postTempMissionWithTitle:tempMissionTitle contnet:tempMissionContent completionTime:cutOffTimeString executors:self.selectedHandlerArray pistures:pictures WithComplete:^(BOOL success) {
        [self.HUD hide:YES];
        if (success) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"sendSucceed", nil)];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}
- (NSArray*)createPictures
{
    NSMutableArray* pictures = [NSMutableArray array];
    for (int i = 0; i < [self.totalImageNameArray count]; i++) {
        YWPatrolPicture* picture = [[YWPatrolPicture alloc] init];
        picture.recordId = [YWCommonTool randStringId];
        picture.pictureId = [YWCommonTool randStringId];
        picture.pictureName = self.totalImageNameArray[i];
        picture.isLocalImage = YES;
        picture.uploadStatus = YWPictureRecordUploadStatusNull;
        picture.recordType = YWPictureRecordTypeTempMission;
        [pictures addObject:picture];
    }
    return pictures;
}
#pragma mark - UIKeyboardNSNotification
- (void)keyboardWillShow:(NSNotification*)notification{
    [self resetDatePicker];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
    if (isShowDatePicker) {
        [self resetDatePicker];
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self resetDatePicker];
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)clickCancelBarButtonEvent:(id)sender{
    if (tempMissionTitle.length>0 || tempMissionContent.length>0 || self.selectedHandlerArray.count>0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"quitEditing", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
